package com.powernode.impl;



import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.powernode.constant.AuthConstants;
import com.powernode.factory.LoginStrategyFactory;
import com.powernode.strategy.LoginStrategy;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * 自己的认证流程
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private LoginStrategyFactory loginStrategyFactory;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //2套系统1个前台1个后台，通过header里面的来区分
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = null;
        if (requestAttributes != null) {
            request = requestAttributes.getRequest();
        }
        //从请求头里面获取登录类型
        String loginType = request.getHeader(AuthConstants.LOGIN_TYPE);
//        if(AuthConstants.SYS_USER_LOGIN.equals(loginType)){
//            //商户后台管理系统
//        }else{
//            //商城前台购物系统
//        }
        if(!StringUtils.hasText(loginType)){
            throw new InternalAuthenticationServiceException("非法登录，登录类型不匹配");
        }
        LoginStrategy instance = loginStrategyFactory.getInstance(loginType);
        if (ObjectUtils.isEmpty(instance)) {
            throw new InternalAuthenticationServiceException("非法登录，登录类型不匹配");
        }
        return instance.realLogin(username);
    }
}
